/**
 * 自定义JS书写处
 */
 var URL ="http://8.129.53.188:9091/"
// var URL = "http://192.168.2.68:9091/"

// 页面加载完加载图标停止转动
window.onload = (function () {
    $('.btn-refresh i').removeClass('fa-spin')
})

// 市场监管主页JS

//画饼状图
// function pieDraw(pieData, marketId) {
//     console.log(111,pieData);
//     // 基于准备好的dom，初始化echarts实例
//     var pieChart = echarts.init(document.getElementById('pie'), 'macarons');
//     let obj = {
//         tooltip: {
//             trigger: 'item',
//             formatter: '{b} <br/>{c} ({d}%)'
//         },
//         series: [{
//             name: '贴标数量',
//             type: 'pie',
//             radius: '55%',
//             gird:{
//                 right:50,
//             },
//             data: pieData,
//             label: {
//                 formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b} }{c}个  ',
//                 // backgroundColor: '#eee',
//                 borderColor: '#aaa',
//                 borderWidth: 1,
//                 borderRadius: 4,
//                 rich: {
//                     a: {
//                         color: '#999',
//                         lineHeight: 22,
//                         align: 'center'
//                     },
//                     hr: {
//                         borderColor: '#aaa',
//                         width: '100%',
//                         borderWidth: 0.5,
//                         height: 0
//                     },
//                     b: {
//                         fontSize: 12,
//                         lineHeight: 33
//                     },
//                     c:{
//                         fontSize: 55,
//                     },
//                     per: {
//                         color: '#eee',
//                         backgroundColor: '#334455',
//                         padding: [2, 4],
//                         borderRadius: 2
//                     }
//                 }
//             },
//             emphasis: {
//                 itemStyle: {
//                     shadowBlur: 10,
//                     shadowOffsetX: 0,
//                     shadowColor: 'rgba(0, 0, 0, 0.5)'
//                 }
//             }
//         }],
//     }
//     // pieChart.on('click', function (params) {
//     //     refreshTableEquipment(marketId, params.data.name) //脚标机销售表
//     // })
//     pieChart.setOption(obj)
// }

// //饼状图ajax
// function pieAjax() {
//     $.ajax({
//         type: 'GET',
//         url:`${URL}SlaughterData/findStaughterRec`,
//         dataType: "json",
//         success: function (data) {
//             console.log(data);
//             if (data.status == 2) {
//                 $('#pie1').parent().parent().addClass('hidden')
//                 return
//             }
//             let dataArr = data.object
//             if (dataArr.length == 0) {
//                 $('#pie1').parent().parent().addClass('hidden')
//                 return
//             }
//             $('#pie1').parent().parent().removeClass('hidden')

//             // let pieData1 = dataArr.map((cur) => {
//             //     const item = {
//             //         value: cur.size,
//             //         name: cur.status
//             //     }
//             //     return item
//             // })

//             pieData1  = data.object;

            
//             pieDraw(pieData1);
//         },
//         error: function (data) { }
//     })
// }

// 大类选择
function selectPoultryFun(marketId) {
    $.ajax({
        type: 'get',
        url: URL + '/PoultrySales/findAll/parent',
        dataType: 'json',
        success: (data) => {
            if (data.status == 2) {
                alert(data.msg)
                return
            }
            data = data.object
            let items = '<option value="all">全部</option>'
            // let poultryId = 'all' //初始化
            data.forEach(e => {
                items += `<option value="${e.id}">${e.poultryParentName}</option>`
            })
            $('#selectPoultry').html(items)
            let poultryParentName = {}
            // poultryParentName = '全部'
            //取得市场的值交给后台
            $("#selectPoultry").change(() => { //大类选择才会变化
                poultryId = $("#selectPoultry").val()
                if (poultryId !== 'all') {
                    poultryParentName = data.find(item => item.id === poultryId)
                    poultryParentName = poultryParentName.poultryParentName
                } else {
                    poultryParentName = '全部'
                }
                //调用柱形图
                barAjax(marketId, poultryId, poultryParentName); //横条形叠加图
                refreshTableSell(marketId, poultryId)
                return
            })
        },
        error: () => {
            // alert('请求市场失败')
        }
    })
}
//画横向条形叠加图
function barDraw(barData, barXAxis, legendData) {
    var barChart = echarts.init(document.getElementById('bar'), 'macarons');
    barChart.clear(); //清除状态
    barXAxis = barXAxis.map(item => {
        let [dateFrom, dateTo] = item.split('~')
        let [dateFromYear, dateFromMonth, datFromDate] = dateFrom.split('-')
        let [dateToYear, dateToMonth, datToeDate] = dateTo.split('-')
        item = `${dateFromMonth}-${datFromDate}~${dateToMonth}-${datToeDate}`
        return item
    })
    barChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: legendData
        },
        xAxis: [{
            type: 'category',
            axisTick: {
                show: false
            },
            data: barXAxis
        }],
        yAxis: [{
            type: 'value'
        }],
        series: barData

    })
}
// 条形图
function barAjax(marketId, poultryId, poultryParentName) {
    $.ajax({
        type: "GET",
        url: `${URL}PoultrySales/findSaleOfParent/to/barchart?houseId=${marketId}&parentId=${poultryId}`,
        dataType: 'json',
        success: function (data) {
            if (data.status == 1) {
                // alert('条形图' + data.msg)
                $('.selectPoultryDiv').parent().parent().addClass('hidden')
                return
            }
            data = data.object
            // 修改判断条件使得某禽类长度为0时候可以显示
            if (data.data.length == 0) {
                $('.selectPoultryDiv').parent().parent().addClass('hidden')
                return
            }
            $('.selectPoultryDiv').parent().parent().removeClass('hidden')
            let barXAxis = data.date
            let legendData = []
            let barData = []
            if (poultryId === 'all') {
                legendData = data.parent_poultry
                let len = data.date.length //每种禽类数据长度，应该与时间长度对应
                barData = data.data.map((item, i) => {
                    // 处理返回空数组情况
                    if (item.length < len) {
                        // 用0填充不足的
                        let start = item.length
                        item.length = len
                        // 从没有数据的位置开始填充0
                        item.fill(0, start, len)
                    }
                    let obj = {
                        name: data.parent_poultry[i],
                        type: 'bar',
                        barGap: 0,
                        label: {
                            show: true,
                            formatter: '{a}\n{c}',
                        },
                        data: item
                    }
                    return obj
                })
            } else {
                let barDataArr = data.data[0]
                barData = [{
                    type: 'bar',
                    label: {
                        show: true,
                        formatter: '{c}只',
                    },
                    data: barDataArr
                }]
                legendData = [poultryParentName]
            }
            barDraw(barData, barXAxis, legendData); //画横向条形叠加图
        },
        error: function (data) {
            // alert('请求出错')
        }
    })
}

//错误信息
function networkError(XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.status === 0) {
        // layer.msg("网络异常，请检查您的网络！");
    } else if (XMLHttpRequest.status === 404) {
        // layer.msg("请求路径不存在，请联系管理员解决！");
    } else if (XMLHttpRequest.status === 500 || XMLHttpRequest.status === 501) {
        // layer.msg("服务器异常，请联系管理员解决！")
    }
}


function del_stall(url, value, name) {
    layer.confirm('该档口下的用户:<br><b style="color:#f20c00">' + name + '</b><br>也会被删除,请谨慎操作!', function () {
        $.ajax({
            url: URL + url + value,
            type: "DELETE",
            // dataType: "json",
            success: function (data) {
                refresh();
                layer.msg("删除成功")
                $(".layui-layer-btn1").click()
            },
            error: function () {
                layer.msg("客户端请求有误");
            }
        })
    })
}
//跳转
function window_change(title, url, val, w, h) {
    url = encodeURI(url + "?code=" + val)
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    if (windowWidth < 640) {
        w = windowWidth
        h = windowHeight * 0.8
    }
    layer_show(title, url, w, h);
}
//获得pathName
function window_pathname() {
    var code = window.location.pathname; //获取url
    code = decodeURI(code.split("/")[1]);
    layer_show(title, url, w, h)
    return code;
}
//开启窗口
function window_show(title, url, w, h) {
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    if (windowWidth < 640) {
        w = windowWidth
        h = windowHeight * 0.8
    }
    layer_show(title, url, w, h);
}
//获取关键值
function get_code() {
    var code = window.location.href; //获取url
    code = decodeURI(code).split("?")[1].split("=")[1];
    return code;
}
/*=============================
 * Cookie
 ==============================*/
//time 单位是  h0.5表示半小时 d表示天  s表示秒
function setCookie(name, value, time) {
    var strsec = getsec(time);
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec * 1);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function getsec(str) {
    var str1 = str.substring(1, str.length) * 1;
    var str2 = str.substring(0, 1);
    if (str2 == "s") {
        return str1 * 1000;
    } else if (str2 == "h") {
        return str1 * 60 * 60 * 1000;
    } else if (str2 == "d") {
        return str1 * 24 * 60 * 60 * 1000;
    }
}

function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else {
        return null;
    }
}

function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

//退出等操作
function logout(username) {
    $.ajax({
        type: "POST",
        url: URL + 'logout',
        async: false,
        data: {
            "username": username
        },
        success: function (data) {
            var remember = getCookie("remember")
            if (remember != 1) {
                delCookie("loginUsername")
                delCookie("loginPassWord")
            }
            delCookie("userid")
            delCookie("roleName")
            sessionStorage.removeItem('pname')
            layer.msg("退出成功");
            setTimeout(function () {
                window.location.href = "login.html"
            }, 1000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            networkError(XMLHttpRequest, textStatus, errorThrown)
        }
    });
}
//点击退出
function tabLogout(username) {
    $('.logout').click(function () {
        logout(username)
    })
}
// 登录验证
function loginCheck() {
    var username = getCookie("loginUsername");
    if (username == null) {
        if (location.pathname.indexOf('/register.html') != -1 || location.pathname.indexOf('/login.html') != -1)
            return
        layer.msg("请先登陆再进行操作");
        setTimeout(function () {
            window.location.href = "login.html"
        }, 1000);
        return false;
    } else if (location.pathname.indexOf('/login.html') == -1) {
        var roleName = getCookie("roleName")
        if (roleName == "屠宰场管理员" && location.pathname.indexOf('/SlaughterhouseRegisterUserAdmin.html') == -1) {
            window.location.pathname = '/SlaughterhouseRegisterUserAdmin.html'
        }
        if (roleName == "农贸市场管理员" && location.pathname.indexOf('/MarketRegisterUserAdmin.html') == -1) {
            window.location.pathname = '/MarketRegisterUserAdmin.html'
        }
        if (roleName == "超级管理员") {
            if (location.pathname.indexOf('/MarketRegisterUserAdmin.html') != -1 || location.pathname.indexOf('/SlaughterhouseRegisterUserAdmin.html') != -1) {
                window.location.pathname = '/index.html'
            }
        }
        return true;
    }
    //请求登录状态
    $.ajax({
        type: "POST",
        url: URL + '/loginuser',
        data: {
            "username": username
        },
        async: false,
        dataType: "json",
        success: function (data) {
            if (data == false) {
                layer.msg("请先登陆再进行操作");
                setTimeout(function () {
                    window.location.href = "login.html"
                }, 1000);
                return false;
            }
            return false;
            // return true;
        },
        error: function (data) {
            if (data == false) {
                layer.msg("请先登陆再进行操作");
                setTimeout(function () {
                    window.location.href = "login.html"
                }, 1000);
                return false;
            }
            return true;
        }
    });
}
document.addEventListener("visibilitychange", function () {
    // 用户打开或回到页面
    if (document.visibilityState === "visible") {
        loginCheck()
    }
});

// 脚标机实时监控登录验证
function loginCheck_stalls() {
    var username = getCookie("loginUsername");
    if (username == null && location.pathname.indexOf('/stallsLogin.html') == -1) {
        layer.msg("请先登陆再进行操作");
        setTimeout(function () {
            window.location.href = "stallsLogin.html"
        }, 1000);
        return false;
    }
    //请求登录状态
    $.ajax({
        type: "POST",
        url: URL + '/loginuser',
        data: {
            "username": username
        },
        async: false,
        dataType: "json",
        success: function (data) {
            if (data == false) {
                layer.msg("请先登陆再进行操作");
                setTimeout(function () {
                    window.location.href = "stallsLogin.html"
                }, 1000);
                return false;
            }
            return false;
        },
        error: function (data) {
            if (data == false) {
                layer.msg("请先登陆再进行操作");
                setTimeout(function () {
                    window.location.href = "stallsLogin.html"
                }, 1000);
                return false;
            }
            return true;
        }
    });
}
//用户模块
function userInfo(username) {
    if (location.pathname == '/ShowBarcodeMachine.html' || location.pathname == '/stallsLogin.html') {
        loginCheck_stalls()
    } else {
        loginCheck()
    }

    $.ajax({
        type: "POST", //post
        url: URL + '/person/login',
        data: {
            "username": username,
        },
        async: false,
        dataType: "json",
        success: function (data) {
            var userRole = data.role
            var userId = data.id
            var head = $('<h5><a href="#">' + username + '</a> </h5>' +
                '<p class="text-muted">' + username + '</p>')
            var info = $(
                // '<li class="dropdown notification-list">' +
                '<a class="nav-link dropdown-toggle nav-user" data-toggle="dropdown" href="#" role="button" aria-haspopup="false" aria-expanded="false">' +
                '<span class="ml-1">' + username + '<i class="mdi mdi-chevron-down"></i> </span>' +
                '</a>' +
                '<div class="dropdown-menu dropdown-menu-right dropdown-menu-animated profile-dropdown">' +
                '<div class="dropdown-item noti-title">' +
                '<h6 class="text-overflow m-0">欢迎使用</h6>' +
                '</div>' +
                '<a href="javascript:void(0);" class="dropdown-item notify-item" onclick="window_change(\'我的信息\',\'message.html\')">' +
                '<i class="fi-head"></i> <span>我的信息</span>' +
                '</a>' +
                // '<a href="javascript:void(0);" class="dropdown-item notify-item">' +
                // '<i class="fi-lock"></i> <span>锁屏</span>' +
                // '</a>' +
                '<a href="javascript:void(0);" class="dropdown-item notify-item logout">' +
                '<i class="fi-power"></i> <span>退出</span>' +
                '</a>' +
                '</div>' +
                '</li>')
            $('.tabUser').html(info)
            tabLogout(username)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            networkError(XMLHttpRequest, textStatus, errorThrown)
        }
    });
}


//发送权限请求
function getRole() {
    var url = window.location.pathname; //获取url
    url = decodeURI(url.split("/")[1]);
    var username = getCookie("loginUsername")
    $.ajax({
        type: "GET",
        url: URL + 'checkOprate?url=/' + url + '&username=' + username,
        data: {},
        async: false,
        dataType: "json",
        success: function (data) {
            data = data.object
            if (data === null) {
                $('.fa-plus').parent().hide()
                $('.fa-th-list').parent().hide()
                $('.fa-edit').parent().hide()
                $('.fa-trash').parent().hide()
            }
            if ($.inArray("t1", data) === -1) {
                $('.fa-plus').parent().hide()
            }
            if ($.inArray("t2", data) === -1) {
                $('.fa-trash').parent().hide()
            }
            if ($.inArray("t3", data) === -1) {
                $('.fa-edit').parent().hide()
            }
            if ($.inArray("t4", data) === -1) {
                $('.fa-th-list').parent().hide()
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            networkError(XMLHttpRequest, textStatus, errorThrown)
        }
    });
}

// 格式化时间
function formatTime(date) {
    if (!date) return ''
    //date是传入的时间
    let d = new Date(date);
    let month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
    let day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
    let hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
    let min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
    let sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();

    let times = d.getFullYear() + '-' + month + '-' + day;

    return times
}

// 获取省市
function getProvince(province, town) {
    $('#province').val(province)
    $.ajax({
        type: 'get',
        url: `${URL}slaughterHouse/findCity?province=${province}`,
        dataType: 'json',
        async: false,
        success: (data) => {
            data = data.object
            // if (data.length === 0) {
            //     alert('该市下没有对应的市场')
            //     return
            // }
            let items = ``
            data = ['中山市']
            data.forEach(e => {
                items += `<option value="${e}">${e}</option>`
            })
            $('#town').html(items)
            $("#town").change(() => {
                town = $("#town").val()
                getDistrict(province, town) //调用区
            })
            getDistrict(province, town)
        },
        error: (data) => {
            // alert('获取省份失败')
        }
    })
}
// 获取区
function getDistrict(province, town) {
    let items = ''
    let data = ['小榄镇', '黄圃镇', '南头镇', '东凤镇', '阜沙镇', '东升镇', '古镇镇', '横栏镇', '三角镇', '民众镇', '南朗镇', '港口镇', '大涌镇', '沙溪镇', '三乡镇', '板芙镇', '神湾镇', '坦洲镇']
    let districtName = data[0] //初始化
    data.forEach(e => {
        items += `<option value="${e}">${e}</option>`
    })
    $('#district').html(items)
    $("#district").change(() => {
        districtName = $("#district").val()
        getMarket(province, town, districtName) //调用区
    })
    getMarket(province, town, districtName)
}
// 获取市场
var tableEquipment, tableSell
//  省/市/区
function getMarket(province, town, district) {
    $.ajax({
        type: 'get',
        url: `${URL}slaughterHouse/findByDistrict2?province=${province}&city=${town}&district=${district}`,
        dataType: 'json',
        async: false,
        success: (data) => {
            if (data.status == 2) {
                // alert(data.msg)
                return
            }
            data = data.object
            let marketId = data[0].id //初始化
            let items = ''
            data.forEach(e => {
                items += `<option value="${e.id}">${e.name}</option>`
            })
            let poultryId = 'all' //初始化
            poultryParentName = '全部'
            $('#market').html(items)
            $("#district").change(() => {
                marketId = $("#market").val()
                if (!marketId) { return }
                marketChange(marketId)
            })
            $("#market").change(() => {
                marketId = $("#market").val()
                if (!marketId) return
                marketChange(marketId)
            })
            // 初始化表格
            getCountMessage(marketId) //获取销量
            getCountMessage1()
            // pieAjax(); //饼图
            // initTableEquipment() //设备表
            barAjax(marketId, poultryId, poultryParentName); //横条形叠加图
            initTableSell(marketId, poultryId) //销售终端表
            selectPoultryFun(marketId)
        },
        error: () => {
            // alert('请求市场失败')
        }
    })
}
// 监听下拉框变化
function marketChange(marketId) {
    selectPoultryFun(marketId) //分类
    getCountMessage(marketId)
    getCountMessage1()
    // pieAjax(); //饼图
    refreshTableEquipment() //设备表
    // 区下拉框，顺便初始化
    barAjax(marketId, 'all', '全部'); //横条形叠加图
    refreshTableSell(marketId, 'all') //销售终端表
}
// 首页设备状态表
// function initTableEquipment() {
//     $.ajax({
//         type: 'GET',
//         url: `${URL}/supervise/topten`,
//         dataType: "json",
//         async: false,
//         success: function (data) {
//             console.log(data);
//             if (data.status == 2) {
//                 $('#tableEquipment').parent().parent().addClass('hidden')
//                 return
//             }
//             let tbody = ''
//             data = data.object
//             for (let k = 0; k < 10; k++) {
//                 // console.log(data);
//                 tbody += '<tr class="text-c">' +
//                     '<td>' + data[k].marketName + '</td>' +
//                     '<td>' + data[k].number + '</td>' +
//                     '<td>' + data[k].type + '</td>' +
//                     '</tr>'
//             }
//             if (data.length == 0) {
//                 $('#tableEquipment').parent().parent().addClass('hidden')
//                 // alert('该市场暂无设备状态数据')
//                 return
//             }
//             $('#tableEquipment').parent().parent().removeClass('hidden')

//             $("#tableEquipmentBody").html(tbody)
//         },
//         error: function (XMLHttpRequest, textStatus, errorThrown) {
//             // networkError(XMLHttpRequest, textStatus, errorThrown)
//             $("#tableEquipmentBody").html('')

//         }
//     });
//     tableEquipment = $('#tableEquipment').DataTable({
//         retrieve: true,
//         "pageLength": 5,
//         "lengthMenu": [5],
//         ordering: false,
//         "lengthChange": false,
//         "searching": false,
//     })
// }
// // 首页销售终端表
function initTableSell(id, poultryId) {
    $.ajax({
        type: "GET",
        url: `${URL}/PoultrySales/findMarkSort/order/by/sale?houseId=${id}&parentId=${poultryId}`,
        async: false,
        dataType: "json",
        success: function (data) {
            if (data.status == 2) {
                $('#tableSell').parent().parent().addClass('hidden')
                return
            }
            let tbody = ''
            data = data.object
            if (data.length == 0) {
                $('#tableSell').parent().parent().addClass('hidden')
                // alert('该市场暂无禽类销售状态数据')
                return
            }
            $('#tableSell').parent().parent().removeClass('hidden')
            for (var i = 0; i < data.length; i++) {
                for (var key in data[i]) {
                    if (data[i][key] == null) {
                        data[i][key] = '';
                    }
                }
                tbody += '<tr class="text-c">' +
                    '<td>' + data[i].poultryType + '</td>' +
                    '<td>' + data[i].saleCount + '</td>' +
                    '<td>' + data[i].toMarketName + '</td>' +
                    '<td>' + data[i].address + '</td>' +
                    '</tr>'
                $("#tableSellBody").html(tbody)
            }


        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('请求禽类销售情况失败')
            $("#tableSellBody").html('')
            return
        }
    });
    tableSell = $('#tableSell').DataTable({
        retrieve: true,
        "pageLength": 6,
        "lengthMenu": [6],
        ordering: false,
        "lengthChange": false,
        "searching": false,
    });
    // }
}
// 重建设备状态表
function refreshTableEquipment() {
    tableEquipment.clear(); //销毁datatable
    tableEquipment.destroy(); //销毁datatable
    // initTableEquipment() //重新加载数据
}
// 重建销售终端表
function refreshTableSell(id, poultryId) {
    tableSell.clear(); //销毁datatable
    tableSell.destroy(); //销毁datatable
    initTableSell(id, poultryId) //重新加载数据
}






// 获取所有父类下的数据
function getCountMessage(marketId) {
    $.ajax({
        type: "GET",
        url: `${URL}PoultrySales/findCountOfParentThisYear/by/house?houseId=${marketId}`,
        dataType: "json",
        success(data) {
            data = data.object
            createHtml1(data)
        },
        error() { }
    })
}

// 生成html
function createHtml(data) {
    let allStr = ''
    for (let item in data) {
        let str = `
        <div class="card border-info mb-3" style="text-align:center;flex-grow:1;border: 1px solid #4eb7eb;">
        <div class="card-header">今年${item == 'all' ? '全部' : item}累计销售</div>
        <div class="card-body text-info">
        <h2 class="card-title">${data[item]}</h2>
        </div>
      </div>`
        allStr += str
    }

    $('.countDiv').html(allStr)
}

// 市场监管页面
// 获取所有父类下的数据
function getCountMessage1(marketId) {
    $.ajax({
        type: "GET",
        // url: `${URL}PoultrySales/findCountOfParentThisYear/by/house?houseId=${marketId}`,
        url:`${URL}supervise/searchnumber`,
        dataType: "json",
        success(data) {
            data = data.object
            createHtml1(data)
        },
        error() { }
    })
}

// 生成html
function createHtml1(data) {
    let allStr = ''
    // data = [100,200,300]
    allStr=`
    <div class="card border-info mb-3" style="text-align:center;flex-grow:1;border: 1px solid #4eb7eb;">
        <div class="card-header">今年累计销售</div>
        <div class="card-body text-info">
        <h2 class="card-title">${data[0]}</h2>
        </div>
    </div>
    <div class="card border-info mb-3" style="text-align:center;flex-grow:1;border: 1px solid #4eb7eb;">
        <div class="card-header">今月累计销售</div>
        <div class="card-body text-info">
        <h2 class="card-title">${data[1]}</h2>
        </div>
      </div>
    <div class="card border-info mb-3" style="text-align:center;flex-grow:1;border: 1px solid #4eb7eb;">
        <div class="card-header">今日累计销售</div>
        <div class="card-body text-info">
        <h2 class="card-title">${data[2]}</h2>
        </div>
      </div>
      `

    $('.countDiv1').html(allStr)
}

// 动态生成上传下载按钮
function operateExcel(layui, urlPost, urlLoad) {
    var parent = document.querySelector(".card-box div");
    //上传按钮
    let btn_onload =
        `<button type="button" id="urlPost" class=" float-left btn btn-primary radius " style="margin-left:1%">导入</button>`
    //指定允许上传的文件类型
    $(parent).append(btn_onload);
    //下载按钮
    let btn_download = `<a href="${URL}${urlLoad}" download id="urlLoad" class=" float-left btn btn-primary radius " style="margin-left:1%">导出</a>`
    $(parent).append(btn_download);

    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#urlPost',
            url: `${URL}${urlPost}`,
            accept: 'file' //普通文件
            ,
            done: function (res) {
                layer.msg('上传成功');
                console.log(res);
            }
        });
    })
}

//用户tab
userInfo(getCookie('loginUsername'))
// 获取form表单传递的数据
$.fn.serializeObject = function () {
    var obj = {};
    var count = 0;
    $.each(this.serializeArray(), function (i, o) {
        var n = o.name, v = o.value;
        count++;
        obj[n] = obj[n] === undefined ? v
            : $.isArray(obj[n]) ? obj[n].concat(v)
                : [obj[n], v];
    });
    //obj.nameCounts = count + "";//表单name个数
    return JSON.stringify(obj);
};